#include "OtsInitHelper.h"
#include <string.h>
#include <stdio.h>

char ots_tmp_str[8];

void OtsInitConfig(void) {
  stc_ots_init_t stcOTSInit;

  (void) OTS_StructInit(&stcOTSInit);
  stcOTSInit.u16ClockSrc = OTS_CLK_XTAL;
  stcOTSInit.u16AutoOffEn = OTS_AUTO_OFF_ENABLE;
  stcOTSInit.f32SlopeK = 737272.73F;
  stcOTSInit.f32OffsetM = 27.55F;

  /* Real XTAL frequency(MHz). */
  //stcOTSInit.stcParaCond.u16ClockFreq = 25U;

  /* 1. Enable OTS peripheral clock. */
  FCG_Fcg3PeriphClockCmd(FCG3_PERIPH_OTS, ENABLE);

  /* 2. Initialize OTS. */
  (void) OTS_Init(&stcOTSInit);

  /* Enable LRC for OTS. */
  // 如果需要进行标定，则需要使用内部低速时钟。否则不用
  //(void)CLK_LrcCmd(ENABLE);

  OtsIrqConfig();


  OtsTriggerConfig();
}

void OtsIrqConfig(void) {
  /* Enable the specified interrupts of OTS. */
  OTS_IntCmd(ENABLE);
}

void OtsTriggerConfig(void) {
  // 启动AOS，EVT_SRC_RTC_PRD，也就是RTC小时中断触发温度读取
  FCG_Fcg0PeriphClockCmd(FCG0_PERIPH_AOS, ENABLE);
  AOS_SetTriggerEventSrc(AOS_OTS, EVT_SRC_RTC_PRD);
}


__IO float32_t m_f32Temperature = 0.0;
void OTS_IrqCallback(void) {
  m_f32Temperature = OTS_CalculateTemp();
  //rt_kprintf("Temperature: %d\n", (int16_t) m_f32Temperature);
	memset(ots_tmp_str, 0, 8);
	sprintf(ots_tmp_str, "%.03f", m_f32Temperature);
	if ( strcmp(chip_device_event.parent.parent.name, "chip_device_event" ) == 0 ) {
		rt_event_send(&chip_device_event, CHIP_DEVICE_EVENT__OTS_FINISHED);
	}
}

rt_err_t Get_Ots_Wait(rt_int32_t timeout) {
	OTS_Start();
	rt_uint32_t e;
	if ( rt_event_recv(&chip_device_event, CHIP_DEVICE_EVENT__OTS_FINISHED, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, timeout, &e) != RT_EOK ){
		rt_kprintf("event error\n");
	}
	return e;
}
